import {Loading} from 'element-ui';
import {getToken} from '@/utils/auth'

export function formatDateRange(date) {
  return (date && date.length) ? {
    beginTime: date[0],
    endTime: date[1]
  } : {}
}

export function exportFile(data, callback) {
  const {url, params, method = "GET", suffix, fileName, download = true} = data;
  const loading = Loading.service({fullscreen: true, text: "正在导出" + fileName, background: "rgba(0, 0, 0, 0.8)"});
  const request = new XMLHttpRequest();
  request.open(method, method === "GET" ? url + params : url, true);
  request.responseType = 'blob';
  request.setRequestHeader('Content-Type', 'application/json');
  request.setRequestHeader("h5ve", getToken());
  request.onload = () => {
    callback && callback();
    if (download) {
      const data = request.response;
      const blob = new Blob([data]);
      const blobUrl = window.URL.createObjectURL(blob);
      const aLabel = document.createElement('a');
      aLabel.style.display = 'none';
      aLabel.download = fileName + new Date().getTime() + suffix;
      aLabel.href = blobUrl;
      aLabel.click();
      try {
        document.body.removeChild(aLabel);
      } catch (e) {

      }
      loading.close();
    }
  };
  request.send(method === "GET" ? null : JSON.stringify(params));
}

/**
 * 对象转Map
 */
export function objectToMap (obj) {
  let map = new Map()
  for (key in obj) {

  }
}
